package com.nys.cqhttp.message.factory.impl;

import com.alibaba.fastjson.JSONObject;
import com.nys.cqhttp.constant.CommonConstant;
import com.nys.cqhttp.mapper.TheMessageMapper;
import com.nys.cqhttp.message.factory.IMessageHandler;
import com.nys.cqhttp.model.Massage;
import com.nys.cqhttp.model.TheMessage;
import com.nys.cqhttp.model.TheMessageExample;
import com.nys.cqhttp.param.Context;
import com.nys.cqhttp.param.MessageParam;
import com.nys.cqhttp.util.Chinese2Number;
import com.nys.cqhttp.util.NumberToCnUtil;
import com.nys.cqhttp.util.SpringContextUtil;
import com.unfbx.chatgpt.OpenAiClient;
import com.unfbx.chatgpt.entity.common.Choice;
import com.unfbx.chatgpt.entity.completions.CompletionResponse;
import com.unfbx.chatgpt.interceptor.OpenAILogger;
import lombok.extern.slf4j.Slf4j;
import okhttp3.logging.HttpLoggingInterceptor;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * DirectUrlMessageHandler
 *
 * @author nysheng
 * @version 1.0.0
 * @description 服务器
 * @date 2021/12/28 19:53
 */
@Slf4j
@Component
public class GPTMessageHandler implements IMessageHandler {
  private static GPTMessageHandler cfwqMessageHandler;
  @Value("${chatGPT.API_KEY}")
  private List<String> apiKeyList;
  @Value("${chatGPT.API_ENDPOINT0}")
  private String apiEndpoint;
  @Value("${proxy.hostname}")
  private String proxyHost;
  @Value("${proxy.port}")
  private Integer proxyPort;
  @PostConstruct
  public void init() throws Exception {
    cfwqMessageHandler = this;
  }

  @Override
  public List<String> listHandler(Massage message, Context context) {
    return Arrays.asList(handler(message, context));
  }

  @Override
  public String handler(Massage messagePojo, Context context) {
    try{
      String message = context.getMessageParam().getMessage();
      //配置api keys
      //代理可以为null
      Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
      //日志输出可以不添加
      HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
      httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
      Random random = new Random();
      OpenAiClient openAiClient = OpenAiClient.builder()
              .apiKey(apiKeyList.get(random.nextInt(apiKeyList.size())))
              .connectTimeout(50)
              .writeTimeout(50)
              .readTimeout(50)
              .interceptor(Arrays.asList(httpLoggingInterceptor))
              .proxy(proxy)
              .build();
      CompletionResponse completions = openAiClient.completions(message.substring(message.indexOf("-")+1,message.length()));
      Choice[] choices = completions.getChoices();
      Choice choice = choices[0];
      return String.format(CommonConstant.CQ_REPLY,context.getMessageParam().getMessageId(),choice.getText().substring(choice.getText().indexOf("\n\n")+2));
    } catch (Exception e) {
      log.info(e.toString());
      return "查询失败";
    }
  }
}
